<?php
/**
 * Created by PhpStorm.
 * User: s.utkin
 * Date: 18.09.14
 * Time: 20:00
 */

namespace Resources\Config;


use PublishedResources\PublishedPackagesConfig;
use Resources\Publisher;

class GenerateRuntimeAction extends \Action {

	/**
	 * Генерирует runtime-конфиг ресурсов \Runtime\PublishedResourcesConfig
	 */
	protected function run()
	{
		$this->response->noRender(true);
		$this->response->noCache(true);

		# Рендерим содержимое конфига
		$packages = $this->request->packages;
		$groups = $this->request->groups;
		$configContent = $this->action('.renderRuntime',
			[
				'packages' => $packages,
				'groups' => $groups,
			]
		);

		# Вычисляем имя файла конфига
		$basePath = realpath(PINENUT_APPLICATION . '/../') . DIRECTORY_SEPARATOR . 'runtime';
		$configPath = $basePath . DIRECTORY_SEPARATOR . 'PublishedResources' . DIRECTORY_SEPARATOR . 'PublishedPackagesConfig.php';
		$configDir = dirname($configPath);

		# Записываем полученное содержимое в файл конфига
		if (!file_exists($configDir)) {
			if (!mkdir ($configDir, 0777, true)) {
				throw new \Exception("Can't create dir: " . $configDir);
			}
		}

		if (file_exists($configPath) && $this->request->safeMode) {
			return;
		}

		if (!file_put_contents($configPath, $configContent)) {
			throw new \Exception("Can't save " . basename($configPath));
		}

		include_once $configPath;
		PublishedPackagesConfig::$config = $packages;
		PublishedPackagesConfig::$groups = $groups;
	}
}